from datetime import date, timedelta

from rest_framework.permissions import IsAdminUser
from rest_framework.views import APIView
from rest_framework.response import Response

from apps.goods.models import GoodsVisitCount
from apps.users.models import User





# 用户总数统计
class UserTotalCountView(APIView):

    # 指定权限
    permission_classes = [IsAdminUser]

    def get(self,request):
        # 1.查询用户，获取用户总数
        count = User.objects.all().count()
        # 2.返回用户总数
        return Response({'count':count})


# 日增用户统计
class UserDayCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 导入当前时间
        now_date = date.today()
        # 查询今日新增用户，获取用户总数
        count = User.objects.filter(date_joined__gte=now_date).count()
        # 返回用户总数
        return Response({'count':count})


# 日活跃用户统计
class UserDayCountActiveView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当前日期
        now_date = date.today()
        # 查找今日登陆用户,统计数量
        count = User.objects.filter(last_login__gte=now_date).count()
        # 返回日活用户总数
        return Response({'count':count})

# 当天下单用户统计
class UserOrderCountView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        # 获取当天日期
        now_date = date.today()
        # 2、根据当天日期查询用户表，获取当天下单用户总数 过滤关联对象查询
        users = User.objects.filter(orderinfo__create_time__gte=now_date)
        data = set(users)
        count = len(data)
        # 返回用户总数
        return Response({'count':count})

# 获取一个月范围内每天注册的用户数量
class UserMonthCountView(APIView):

    def get(self,request):
        # 获取当天日期
        now_date = date.today()
        # 获取一个月之前的日期
        start_date = now_date-timedelta(30)
        # 从30天前开始循环遍历获取每天注册的用户总数
        date_list = []
        for i in range(30):
            # 指定当天日期
            first_day = start_date + timedelta(i)
            # 指定下一天日期
            next_day = first_day + timedelta(1)
            count = User.objects.filter(date_joined__gte=first_day,date_joined__lt=next_day).count()
            date_list.append({
                'count':count,
                'date':first_day,
            })
        # 返回注册用户总数和当天日期
        return Response(date_list)

# 日分类商品访问量
class GoodsTypeVisitView(APIView):

    permission_classes = [IsAdminUser]

    def get(self,request):
        #获取当前日期
        now_date = date.today()
        # 查询当天的访问情况，并遍历获取商品类型和对应访问量
        data = GoodsVisitCount.objects.filter(date__gte=now_date)
        data_list = []
        for goods in data:
            data_list.append({
                'count':goods.count,
                'category':goods.category.name,
            })
        # 返回数据
        return Response(data_list)

